<?php
add_filter('template_include', 'gzdsx_pos_template');
function gzdsx_pos_template($template)
{
    global $post;

    if (!$post) {
        return $template;
    }

    // Return default template if we don't have a custom one defined.
    $post_page_template = get_post_meta($post->ID, '_wp_page_template', true);
    $file = get_stylesheet_directory() . '/' . $post_page_template;
    if (file_exists($file)) {
        return $file;
    }

    $file = get_template_directory() . '/' . $post_page_template;
    if (file_exists($file)) {
        return $file;
    }

    $file = GZDSX_POS_TEMPLATE_PATH . $post_page_template;

    return file_exists($file) ? $file : $template;
}